package com.example.project02.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.project02.common.Constants;
import com.example.project02.controller.dto.UserDTO;
import com.example.project02.entity.User;
import com.example.project02.exception.ServiceException;
import com.example.project02.mapper.UserMapper;
import com.example.project02.utils.TokenUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static org.springframework.boot.Banner.Mode.LOG;

@Service
public class UserService extends ServiceImpl<UserMapper,User> {

    public boolean saveuser(User user) {
//        Integer id = user.getId();
//        if (id==null || id==0) {
//            return save(user);   //mybatis-plus提供的方法，表示插入数据
//        }else {
//            return updateById(user);
//        }
        return saveOrUpdate(user);
    }


    public UserDTO login(UserDTO userDTO) {
        User one = getUserInfo(userDTO);
        if(one!=null){
            BeanUtil.copyProperties(one,userDTO,true);
//            String token = TokenUtils.genToken(one.getId().toString(), one.getPassword());
            String token = TokenUtils.genToken(String.valueOf(one.getId()), one.getPassword());
            userDTO.setToken(token);
            return userDTO;
        }else{
            throw new ServiceException(Constants.CODE_600,"用户名或密码错误");
        }

    }

    public User register(UserDTO userDTO) {
        User one = getUserInfo(userDTO);
        if(one==null){
            one=new User();
            BeanUtil.copyProperties(userDTO,one,true);
            save(one);
        }else{
            throw new ServiceException(Constants.CODE_600,"用户已存在");
        }
        return one;
    }
    private User getUserInfo(UserDTO userDTO){
        QueryWrapper<User> querywrapper=new QueryWrapper<>();
        querywrapper.eq("username",userDTO.getUsername());
        querywrapper.eq("password",userDTO.getPassword());
        User one;
        try{
            one = getOne(querywrapper);
        }catch(Exception e){
            throw new ServiceException(Constants.CODE_500,"系统错误");
        }
        return one;
    }

//    @Autowired
//    private UserMapper userMapper;
//    public int save(User user){
//        Integer id = user.getId();
//        if (id==null || id==0) {
//            return userMapper.insert(user);   //mybatis-plus提供的方法，表示插入数据
//        }else {
//            return userMapper.update(user);
//        }
//    }
}
